<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>数据处理</title>
        <link rel="stylesheet" type="text/css" href="/webapp/css/easyui.css">
        <link rel="stylesheet" type="text/css" href="/webapp/css/icon.css">
        <link rel="stylesheet" type="text/css" href="/webapp/css/color.css">
        <link rel="stylesheet" type="text/css" href="/webapp/css/public.css">
        <script type="text/javascript" src="/webapp/js/lib/jquery.min.js"></script>
        <script type="text/javascript" src="/webapp/js/lib/jquery.easyui.min.js"></script>
        <script type="text/javascript" src="/webapp/js/lib/jquery.global.settings.js"></script>
        <script type="text/javascript" src="/webapp/js/lib/ajaxfileupload.js"></script>
        <script type="text/javascript" src="/webapp/js/lib/aliyun-oss-sdk.min.js"></script>
        <script type="text/javascript" src="/webapp/js/common/config.js"></script>
        <script type="text/javascript" src="/webapp/js/lib/xlsx.full.min.js"></script>
        <script type="text/javascript" src="/webapp/js/common/export.js"></script>
    </head>
    <body>
        <div class="easyui-container-fluid">
            <div class="easyui-panel" style="border: none;">
                <div class="nav" id="nav"></div>
                <div class="easyui-panel" style="border:none;">
                    <form id="ff">
                        <div style="margin-bottom:20px;">
                            <label class="item-label">年份：</label>
                            <select class="easyui-combobox" name="year" id="year" style="width:100px;"></select>
                            <label class="item-label">原始品类：</label>
                            <input type="text" class="easyui-textbox" name=originalCategory style="width:100px;"/>
                            <label class="item-label">原始品牌：</label>
                            <input type="text" class="easyui-textbox" name=originalBrand style="width:100px;"/>
                            <label class="item-label">原始型号：</label>
                            <input type="text" class="easyui-textbox" name=originalModel style="width:100px;"/>
                            <label class="item-label">原始商场：</label>
                            <input type="text" class="easyui-textbox" name=originalMall style="width:100px;"/>
                            <label class="item-label">空值类型：</label>
                            <select class="easyui-combobox" name="filterType" data-options="panelHeight:'auto'" style="width:100px;">
                                <option value="">-请选择-</option>
                                <!--<option value="CHANNEL_IS_NULL">渠道码为空</option>-->
                                <option value="MALL_IS_NULL">商场码为空</option>
                                <option value="MALL_IS_DISABLE">商场已禁用</option>
                            </select>
                            <label class="item-label">量|价|额：</label>
                            <select name="dataTotal" class="easyui-combobox" data-options="panelHeight:'auto'" style="width:80px;">
                                <option value="">-请选择-</option>
                                <option value="true">显示</option>
                                <option value="false" selected>不显示</option>
                            </select>
                        </div>
                        <div style="margin-bottom:20px;" id="parent">
                        <span id="monthLabel">
                            <label class="item-label">月：</label>
                            <input type="text" id="month" name="month" class="easyui-combobox" style="width: 100px;">
                        </span>
                            <span id="weekLabel">
                            <label class="item-label">周：</label>
                            <input type="text" id="week" name="week" class="easyui-combobox" style="width: 100px;">
                        </span>
                            <label class="item-label" id="label-for-channel" style="margin-left: 0px;">渠道：</label>
                            <select id="channel" name="channelCode" class="easyui-combobox" style="width: 100px;">
                            </select>
                            <label class="item-label">商场：</label>
                            <input class="easyui-combobox" name="mallCode" id="mall" style="width:100px;" prompt="请先选择渠道" ,/>
                            <label class="item-label">状态：</label>
                            <input id="entityStatus" class="easyui-switchbutton" checked style="width:80px;height:30px;" onText="启用" offText="禁用">
                            <label class="item-label">异常数据：</label>
                            <select class="easyui-combobox" name="retailResult" data-options="panelHeight:'auto'" style="width:160px;">
                                <option value="">-请选择-</option>
                                <option value="UNUSUAL_500">1.销量>=500且100倍数</option>
                            </select>
                            <a class="easyui-linkbutton c8" style="margin-left:40px;width:80px;" onclick="searchBy()">查询</a>
                            <input type="button" class="easyui-linkbutton" onclick="exportData()" value="导出" style="margin-left:47px;height: 32px;;width:80px;background:#cde5fd"/>
                            <input type="button" class="easyui-linkbutton" onclick="importData()" value="导入" style="height: 32px;;width:80px;background:#cde5fd"/>
                        </div>
                    </form>
                </div>
                <div class="table-wrapper">
                    <table id="datagrid" style="width:100%;" idField="id" data-options="fitColumns:true,scrollbarSize:0">
                        <!--<a href="javascript:void(0);" class="easyui-linkbutton c8" style="width:80px" onclick="batchDelete()">批量删除</a>-->
                        <thead>
                            <tr>
                                <th data-options="field:'id',checkbox:true,align:'center'"></th>
                                <th data-options="field:'uploadRecordCode',align:'center'" width="120">文件批号</th>
                                <th data-options="field:'channelName',align:'center'" width="80">渠道</th>
                                <th data-options="field:'mallName',align:'center',formatter:mallFormatter" width="80">商场</th>
                                <th data-options="field:'originalMall',align:'center'" width="80">原始商场</th>
                                <th data-options="field:'originalCategory',align:'center',formatter:categoryFormatter" width="120">原始|系统品类</th>
                                <th data-options="field:'originalBrand',align:'center'" width="80">原始品牌</th>
                                <th data-options="field:'originalModel',align:'center'" width="160">原始型号</th>
                                <th data-options="field:'count',align:'center'" width="60">销量</th>
                                <th data-options="field:'price',align:'center'" width="60">单价</th>
                                <th data-options="field:'total',align:'center'" width="80">销额</th>
                                <th data-options="field:'entityStatus',align:'center',formatter:statusFormatter" width="40">状态</th>
                                <th data-options="field:'action',align:'center',formatter:actions" width="90">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div id="uploadFile" class="easyui-window upload-wrapper" title="导入文件" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:400px;height:200px;padding:10px;">
            <form id="window-form">
                <div style="margin-bottom:20px;">
                    <label class="item-label">选择文件：</label>
                    <input id="upload" multiple="multiple" style="width:230px;"/>
                </div>
                <div style="margin-bottom:20px;text-align:center">
                    <a style="width:80px;" href="javascript:void(0);" class="easyui-linkbutton c8" onclick="uploadFile()">保存</a>
                </div>
            </form>
        </div>
    </body>
    <script type="text/javascript">
        var globalData = [];
        $(function () {
            setNav();
            initMonthWeek("monthLabel", "weekLabel");
            var height = $(window).height();
            var nav_height = $("#nav")._outerHeight();
            var ff_height = $("#ff").height();
            var table_height = height - nav_height - ff_height - 20;
            $("#datagrid").css("max-height", table_height);
            $("#datagrid").datagrid({
                pagination: true,
                rownumbers: true,
                checkOnSelect: false,
                // columns:[dg_columns],
                onBeforeSelect: function (index, row) {
                    window.currentRecord = row;
                    // leftDirectionFun();
                    return false;
                },
                onLoadSuccess: function (data) {
                    $("#datagrid").datagrid("clearChecked");
                    var stats = "<div class='stats'><label>销量 ：{{totalCount}}</label>&nbsp;&nbsp;&nbsp;<label>金额 ：{{totalPrice}}</label>&nbsp;&nbsp;&nbsp;<label>均价 ：{{avgPrice}}</label></div>";
                    stats = stats.replace("{{totalCount}}", globalData.map.totalCount);
                    stats = stats.replace("{{totalPrice}}", globalData.map.totalPrice);
                    stats = stats.replace("{{avgPrice}}", globalData.map.avgPrice);
                    $(".datagrid-wrap").find(".stats").remove();
                    $(".datagrid-wrap").append(stats);
                },
                toolbar: [{
                    text: '批号禁用',
                    handler: function () {
                        batchDisableHandler();
                    }
                }, '-', {
                    text: '批量禁用',
                    handler: function () {
                        batchDeletejl();
                    }
                }, '-', {
                    text: "商场：" +
                    "<input class=\"easyui-combobox\" name=\"mallCode\" id=\"mall2\" placeholder=\"请先选择渠道\" style=\"width:100px;\"/>"
                }, '-', {
                    text: "修改商场",
                    handler: function () {
                        updateMall();
                    }
                }
                ]
            }).datagrid("getPager").pagination({
                onSelectPage: searchBy
            });
            initChannelSelect("channel", "mall", 0, "mall2");
            // searchBy(1,100);
            aRecords("数据处理","/webapp/pages/channel/salesDetail/list")
        });
        $(".column-list-select").delegate("input", "click", function (e) {
            var self = this;
            var columns = getColumns();
            $("#datagrid").datagrid({
                columns: [columns],
                data: globalData
            });
        });

        function actions(val, row) {
            var disableText = row.entityStatus == "OK" ? "禁用" : "启用";
            var disableStatus = row.entityStatus == "OK" ? "DISABLE" : "OK";
            return "<a href='javascript:void(0);' class='easyui-linkbutton l-btn l-btn-small' style='width:60px' " +
                "onclick='updateStatus(\"" + row.id + "\",\"" + disableStatus + "\")'>" + disableText + "</a>";
        }

        function updateStatus(data, status) {
            var message = status == "OK" ? "您确定启用该记录吗?" : "您确定禁用该记录吗?";
            $.messager.confirm("提示", message, function (flag) {
                if (flag) {
                    $.ajax({
                        url: config.url + "/channelSalesData/" + data,
                        type: 'DELETE',
                        data: {entityStatus: status},
                        xhrFields: {withCredentials: true},
                        success: function (data) {
                            $.messager.alert("提示", "操作成功", "info", function () {
                                searchBy(1, 100);
                            });
                        },
                        error: function (XMLHttpRequest, textStatus, thrown) {

                        }
                    });
                }
            });
        }

        function searchBy(page, size) {
            var data = getFormData(document.getElementById("ff"));
            if (!isMonthType() && !data.week) {
                data.week = window.parent.timeData.weekInYear;
            }
            data.reportType = window.parent.workMode.toUpperCase();
            data.entityStatus = $("#entityStatus").switchbutton("options").checked == true ? "OK" : "DISABLE";
            data['page'] = page || 1;
            data['size'] = size || 100;
            $.ajax({
                url: config.url + "/channelSalesData",
                type: "get",
                data: transfer(data),
                xhrFields: {withCredentials: true},
                beforeSend: function () {
                    $.messager.progress({
                        title: "请稍等",
                        interval: 50,
                        text: "数据加载中..."
                    });
                },
                complete: function () {
                    $.messager.progress("close");
                },
                success: function (data) {
                    $.messager.progress("close");
                    if (data) {
                        globalData = data;
                        $("#datagrid").datagrid("loadData", data);
                    }
                },
                error: function (data) {
                    $.messager.progress("close");
                }
            });

        }

        function channelFormatter(value, row, index) {
            return value + "|(" + row.channelCode + ")";
        }

        function mallFormatter(value, row, index) {
            return value + "|(" + row.mallCode + ")";
        }

        function categoryFormatter(value, row, index) {
            return value + "|(" + row.categoryName + ")";
        }

        function batchDisableHandler() {
            var selectedRow = $("#datagrid").datagrid("getChecked");
            if (selectedRow != null && selectedRow.length > 0) {
                var codes = selectedRow.map(function (item) {
                    return item.uploadRecordCode;
                });
                var data = codes[0];
                $.messager.confirm("提示", "您确定禁用吗?", function (r) {
                    if (r) {
                        $.ajax({
                            url: config.url + "/channelSalesData/batchDelete/" + data,
                            type: 'DELETE',
                            xhrFields: {withCredentials: true},
                            success: function (data) {
                                $.messager.alert("提示", "操作成功", "info", function () {
                                    searchBy(1, 100);
                                });
                            },
                            error: function (XMLHttpRequest, textStatus, thrown) {

                            }
                        });
                    }
                });
            } else {
                $.messager.alert("提示", "请选择相关记录", "error");
                return false;
            }
        }

        function batchDeletejl() {
            //datagrid重载默认值   getChecked获取勾选集合
            var selectedRow = $("#datagrid").datagrid("getChecked");
            if (selectedRow != null && selectedRow.length > 0) {
                var codes = selectedRow.map(function (item) {
                    return item.id;
                });
                $.messager.confirm("提示", "您确定禁用所选吗?", function (r) {
                    if (r) {
                        $.ajax({
                            url: config.url + "/channelSalesData/deleteList",
                            type: 'POST',
                            xhrFields: {withCredentials: true},
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            data: JSON.stringify(codes),
                            success: function (codes) {
                                $.messager.alert("提示", "操作成功", "info", function () {
                                    searchBy(1, 100);
                                });
                            },
                            error: function (XMLHttpRequest, textStatus, thrown) {

                            }
                        });
                    }
                });
            } else {
                $.messager.alert("提示", "请选择相关记录", "error");
                return false;
            }
        }

        function updateMall() {
            var selectedRow = $("#datagrid").datagrid("getChecked");
            if (selectedRow != null && selectedRow.length > 0) {
                var codes = selectedRow.map(function (item) {
                    return item.id;
                });
                var ids = "";
                var mallCode = $("#mall2").val();
                for (var id of codes) {
                    ids += id + ",";
                }
                $.messager.confirm("提示", "您确定要修改商场吗?", function (r) {
                    if (r) {
                        $.ajax({
                            url: config.url + "/channelSalesData/updateMall",
                            type: 'POST',
                            xhrFields: {withCredentials: true},
                            dataType: 'json',
                            data: {ids: ids, mallCode: mallCode},
                            success: function (codes) {
                                if (codes.code == 200) {
                                    $.messager.alert("提示", codes.msg, "info", function () {
                                        searchBy(1, 100);
                                        $('#mall2').combobox('clear');
                                    });
                                } else {
                                    $.messager.alert("提示", codes.msg, "error");
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, thrown) {
                            }
                        });
                    }
                });
            } else {
                $.messager.alert("提示", "请选择相关记录", "error");
                return false;
            }
        }

        function exportData() {
            var data = getFormData(document.getElementById("ff"));
            if (!isMonthType() && !data.week) {
                data.week = window.parent.timeData.weekInYear;
            }
            data.entityStatus = $("#entityStatus").switchbutton("options").checked == true ? "OK" : "DISABLE";
            data.reportType = window.parent.workMode.toUpperCase();
            $.messager.confirm("提示", "您确定要导出数据吗?", function (r) {
                if (r) {
                    $.ajax({
                        url: config.url + "/channelSalesData/exportData",
                        type: "POST",
                        // contentType: "multipart/form-data",
                        data: transfer(data),
                        dataType: "json",
                        xhrFields: {withCredentials: true},
                        beforeSend: function () {
                            $.messager.progress({
                                title: "请稍等",
                                interval: 50,
                                text: "数据加载中..."
                            });
                        },
                        complete: function () {
                            $.messager.progress("close");
                        },
                        success: function (result) {
                            $.messager.progress("close");
                            if (result.code == 200) {
                                json_to_blob(result.msg.data, result.msg.columnNum, result.msg.fileName, "sheet");
                            } else {
                                $.messager.alert("提示", result.msg, "error");
                            }
                        },
                        error: function (msg) {
                            $(".notice").html('Error:' + msg);
                        }
                    })
                }
            });
        }

        function importData() {
            $("#uploadFile").window("open");
            $("#upload").filebox({
                buttonText: "选择文件",
                multiple: true

            });
        }
        function uploadFile() {
            var datas = getFormData(document.getElementById("ff"));
            datas.reportType = window.parent.workMode.toUpperCase();
            //上传阿里云文件
            $.ajax({
                url: config.url + "/aliyun/getTokenToAI",
                data: datas,
                xhrFields: {withCredentials: true},
                beforeSend: function () {
                    $.messager.progress({
                        title: "请稍等",
                        interval: 50,
                        text: "数据加载中..."
                    });
                },
                success: function (data) {
                    if(data.code!=200){
                        $.messager.alert("提示",data.msg,"error");
                        $.messager.progress("close");
                        return;
                    }
                    var client = new OSS({
                        region: data.msg.region,
                        accessKeyId: data.msg.accessKeyId,
                        accessKeySecret: data.msg.accessKeySecret,
                        stsToken: data.msg.stsToken,
                        bucket: data.msg.bucket
                    });
                    var file=$("input[type='file']")[0].files[0];

                    async function putBlob(path) {
                        try {
                            var result = await client.put(path + file.name, file);
                            datas.filePath = result.name;
                            console.log(result);
                            console.log(datas);
                            $.ajax({
                                url: config.url + "/channelSalesData/saveUploadAI",
                                xhrFields: {withCredentials: true},
                                data: datas,
                                type: "POST",
                                success: function (d) {
                                    $("#uploadFile").window("close");
                                    $.messager.alert("提示",d.msg,"info");
                                    $.messager.progress("close");
                                },
                                error: function () {
                                    $.messager.progress("close");
                                }
                            });

                        } catch (e) {
                            console.log(e);
                        }
                    }

                    putBlob(data.msg.path);
                },
                error: function () {
                    $.messager.progress("close");
                }
            })
        }
    </script>
</html>